﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace BibleReader
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();

			
		}

		private Bible _Bible;

		private void button1_Click(object sender, EventArgs e)
		{
			string biblePath = "../../data/hb5/hb5.txt";
			Thread t = new Thread(new ThreadStart(delegate()
			{
				this.Invoke(new MethodInvoker(delegate(){ this.button1.Enabled = false; }));
				try
				{
					Console.WriteLine("Start reading Bible!");

					_Bible = new Bible();

					// http://stackoverflow.com/questions/336781/how-to-read-a-chinese-text-file-from-c
					System.IO.StreamReader r = new System.IO.StreamReader(biblePath, System.Text.Encoding.GetEncoding("big5"));
					string line;
					while (null != (line = r.ReadLine()))
					{
						string[] tokens = line.Split(new char[] { ' ', ':' }, 4);
						if (tokens.Length != 4) continue;

						int chapter, verse;
						if (!int.TryParse(tokens[1], out chapter)) continue;
						if (!int.TryParse(tokens[2], out verse)) continue;

						string bookName = tokens[0].ToUpper();

						Book bookObj = _Bible.GetBook(bookName);

						if (null == bookObj)
						{
							// create book if needed
							bookObj = new Book();
							bookObj.Name = bookName;
							_Bible.Books.Add(bookObj);
						}

						while (bookObj.Chapters.Count < chapter)
						{
							// create chapters if needed
							bookObj.Chapters.Add(new Chapter());
						}

						Chapter chapterObj = bookObj.Chapters[chapter - 1];
						chapterObj.Verses.Add(tokens[3]);

						//this.Invoke(new MethodInvoker(delegate() {this.richTextBox1.AppendText(line + "\n");}));
					}

					this.Invoke(new MethodInvoker(delegate() { this.bookView.SetObjects(_Bible.Books); }));

					Console.WriteLine("Done!");
				}
				catch (Exception err)
				{
					Console.WriteLine(err.ToString());
				}
				this.Invoke(new MethodInvoker(delegate() { this.button1.Enabled = true; }));
			}
			));

			t.Start();
		}

		private void bookView_SelectionChanged(object sender, EventArgs e)
		{
			if (bookView.SelectedObject == null)
				return;

			this.richTextBox1.Clear();
			int c = 1;
			foreach (var ch in (bookView.SelectedObject as Book).Chapters)
			{
				int v = 1;
				foreach (var verse in ch.Verses)
				{
					this.richTextBox1.AppendText(String.Format("{0}:{1}", c, v));
					this.richTextBox1.AppendText(verse);
					++v;
				}

				this.richTextBox1.AppendText("\n");
				++c;
			}
		}
	}
}
